//
//  RECFastNewsController.m
//  CarFace
//
//  Created by dlios on 15/4/1.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "RECFastNewsController.h"
#import "RecFastCell.h"
#import "Attachments.h"
#import "Commentlist.h"
#import "NewsData.h"
#import "Articlemodel.h"
#import "FastResult.h"
#import "Messagelist.h"


#define UImageWidth self.view.bounds.size.width

#define UImageHeight UImageWidth * 0.625

@interface RECFastNewsController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *messagelistArr;
@property(nonatomic, retain)FastResult *fastResult;
@property(nonatomic, retain)UIImageView *headImageView;
@property(nonatomic, retain)NSMutableArray *att;
@property(nonatomic, assign)CGFloat *photoheight;
//加载属性
@property(nonatomic, retain)HaveAEasyHUD *mub;

@end

@implementation RECFastNewsController
- (void)dealloc
{
    [_fastResult release];
    [_headImageView release];
    [_tableView release];
    [_messagelistArr release];
    [_idStr release];
    [super dealloc];
}
- (void)handleData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:_idStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"%@", result);
        _fastResult = [[FastResult alloc] initWithDictionary:[result objectForKey:@"result"]];
//        NSLog(@"%@", fast.messagelist);
        [self.messagelistArr addObjectsFromArray:_fastResult.messagelist];
        for (Messagelist *mes in _messagelistArr) {
            for (NSInteger i = 0; i < mes.attachments.count; i++) {
                Attachments *att = [Attachments objectWithDictionary:mes.attachments[i]];
                [mes.att addObject:att];
            }
            for (NSInteger i = 0; i < mes.commentlist.count; i++) {
                Commentlist *com = [Commentlist objectWithDictionary:mes.commentlist[i]];
                [mes.com addObject:com];
            }
//            NSLog(@"att:%@\n\nmes:%@", mes.att, mes.com);
        }
        
       
        NSString *str = self.fastResult.newsData.img;
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str];
        [_headImageView setImageWithURL:url];
        [self.tableView reloadData];
        //删除
        [_mub hudWasHidden:_mub.progressHud];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    NSLog(@"%@" ,_idStr);
    self.messagelistArr = [NSMutableArray array];
    [self handleData];
    
    self.view.backgroundColor = [UIColor blackColor];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [_tableView release];
    [_tableView registerClass:[RecFastCell class] forCellReuseIdentifier:@"tableview"];
    
    self.headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -UImageHeight, UImageWidth, UImageHeight)];
//    self.headImageView.backgroundColor = [UIColor yellowColor];
    self.headImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.tableView insertSubview:_headImageView atIndex:0];
    self.tableView.contentInset = UIEdgeInsetsMake(0.6 * UImageHeight, 0, 0, 0);
    
    
    //加载
    self.mub = [[HaveAEasyHUD alloc] initOneProgressHud:self.view];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"<" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor blackColor];
    button.alpha = 0.5;
    button.frame = CGRectMake(15, 50, 60, 30);
    [self.view addSubview:button];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    NSLog(@"number  %ld", self.messagelistArr.count);
    if (_messagelistArr.count == 0) {
        return 0;
    } else {
//    NSLog(@"%ld", _messagelistArr.count);
        return self.messagelistArr.count;
    }
}

//cell们
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecFastCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableview"];
//    NSLog(@"------------%@", [self.messagelistArr[indexPath.row] content]);
    Messagelist *mess = _messagelistArr[indexPath.row];
    cell.mess = mess;
//    NSLog(@"%@", [mess content]);
    return cell;
}

- (void)buttonAction:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//自定义cell高度自适应
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    //文字的自适应告诉
    NSString *str = [_messagelistArr[indexPath.row] content];
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width , 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    //图片的自适应高度
    Messagelist *mess = _messagelistArr[indexPath.row];
    CGFloat destion = 0;
    for (NSInteger i = 0; i < mess.att.count; i++) {
        Attachments *att = mess.att[i];
        CGFloat hei = [att.height floatValue];
        CGFloat wid = [att.width floatValue];
        CGFloat photoHeight = self.view.frame.size.width * 48 / 50 * hei / wid;
        
        destion  += photoHeight + self.view.frame.size.width / 50;
//        NSLog(@" PhotoHeight:\n--%ld--%lf", i, photoHeight);
    }
    
//    NSLog(@"\n\n\n\n\n---- %lf \n---- %ld", destion, mess.att.count);
    return rect.size.height + 100 + destion;
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 向下拽了多少距离
    CGFloat down = - (UImageHeight * 0.5) - scrollView.contentOffset.y;
    if (down < -100) return;
    
    CGRect frame = self.headImageView.frame;
    // 2 决定图片变大的速度,值越大,速度越快
    frame.size.height = UImageHeight + down * 2;
    self.headImageView.frame = frame;
}

// 让tableView处于不能被选中的状态
- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
